﻿
var getCss = function (o, key) {
    return o.currentStyle ? o.currentStyle[key] : document.defaultView.getComputedStyle(o, false)[key];
};

function startDrag(bar, target, callback) {
    var params = {
        left: 0,
        top: 0,
        currentX: 0,
        currentY: 0,
        flag: false
    };
    if (getCss(target, "left") !== "auto") {
        params.left = getCss(target, "left");
    }
    if (getCss(target, "top") !== "auto") {
        params.top = getCss(target, "top");
    }
    bar.onmousedown = function (event) {
        params.flag = true;
        if (!event) {
            event = window.event;
            bar.onselectstart = function () {
                return false;
            }
        }
        var e = event;
        params.currentX = e.clientX;
        params.currentY = e.clientY;
    };
    document.onmouseup = function () {
        params.flag = false;
        if (getCss(target, "left") !== "auto") {
            params.left = getCss(target, "left");
        }
        if (getCss(target, "top") !== "auto") {
            params.top = getCss(target, "top");
        }
    };
    document.onmousemove = function (event) {
        var e = event ? event : window.event;
        if (params.flag) {
            var nowX = e.clientX, nowY = e.clientY;
            var disX = nowX - params.currentX, disY = nowY - params.currentY;
            var _left = parseInt(params.left) + disX;
            //不能超出左边距
            if (_left < 0)
                _left = 0;
            //不能超出右边距太多
            //if (document.body.clientWidth - $(target).offset().left > target.clientWidth / 2)
            //    _left = target.clientWidth / 2-2;

            target.style.left = _left + "px";

            //console.log(document.body.clientWidth + "  " + $(target).offset().left + " " + target.clientWidth / 2)
            //不能超出上边距
            var _top = parseInt(params.top) + disY;
            if (_top < 0)
                _top = 0;
            target.style.top = _top + "px";
            if (event.preventDefault) {
                event.preventDefault();
            }
            return false;
        }

        if (typeof callback == "function") {
            callback(parseInt(params.left) + disX, parseInt(params.top) + disY);
        }
    }
};